# -*- coding: utf-8 -*-
# @Time    : 2025-08-11 16:25
# @Author  : Daniel

import requests
from bs4 import BeautifulSoup
from requests.exceptions import RequestException

def get_html(url):
    try:
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
        response = requests.get(url, timeout=30, headers=headers)
        response.encoding = response.apparent_encoding

        if response.status_code == 200:
            return response.text

        return None
    except RequestException:
        return None


def get_bank(soup):
    table = soup.find_all('table')[1]

    dataAll = {}

    for all_tr in table.find_all('tr'):
        all_td = all_tr.find_all('td')

        if len(all_td) > 0:
            num = 0
            currency_name = all_td[0].text

            rate = 0

            if all_td[1].text != '':
                rate = float(all_td[1].text)
            elif all_td[2].text != '':
                rate = float(all_td[2].text)

            dataAll[currency_name] = rate/100

    return dataAll

def get_rate_date():
    url = "https://www.bankofchina.com/sourcedb/whpj/"

    html = get_html(url)

    soup = BeautifulSoup(html, 'lxml')
    bank = get_bank(soup)

    # print(bank)
    return bank

if __name__ == '__main__':
    safe = get_rate_date()
    print('美元:', safe['美元'])
    print('日元:', safe['日元'])
    print('新台币:', safe['新台币'])
